/*初始化方法*/
function init() {
    let layer = layui.layer, form = layui.form;
    // 0.1加载分类
    $.get("/typeInfo", {"token": localStorage.getItem("token")}, function (result) {
        if (result.code === 200) {
            let html_str = '<option value="">请选择</option>';
            $.each(result.data, function (i, n) {
                html_str += '<option value="' + n.id + '">' + n.name + '</option>';
            })
            $("select[name='type_id']").html(html_str);
            form.render('select'); //刷新select选择框渲染
            // 0.2 加载创建标记
            load_create_flag(layer, form);
        } else if (result.code === 401) {
            layer.msg(result.msg, {icon: 5});
            window.location.href = "/login.html";
        } else
            layer.msg(result.msg, {icon: 5});
    })
}

layui.use(['layer', 'form'], function () {
    let form = layui.form;
    // 1.发布按钮
    form.on('submit(form_publish)', function (data) {
        //console.log(data.elem) //被执行事件的元素DOM对象，一般为button对象
        //console.log(data.form) //被执行提交的form对象，一般在存在form标签时才会返回
        //console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
        insert_update_blog(true);
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });
    // 2.保存按钮
    form.on('submit(form_save)', function (data) {
        //console.log(data.elem) //被执行事件的元素DOM对象，一般为button对象
        //console.log(data.form) //被执行提交的form对象，一般在存在form标签时才会返回
        //console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
        insert_update_blog(false);
        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
    });

    // 开始初始化
    init();
})

/*插入博客或者修改博客的函数*/
function insert_update_blog(published) {
    let layer = layui.layer;
    let insert_load_index = layer.load(1);
    let tag = [];
    let $tag_checked = $("input[type='checkbox'][name='tag']:checked");
    if ($tag_checked.length === 0) {
        layer.close(insert_load_index);
        layer.msg("请选择标签", {icon: 5});
        return false;
    }
    $.each($tag_checked, function (i, n) {
        tag[i] = n.value;
    })
    $.ajax({
        url: "/blog",
        method: (window.parent.$("#blog_edit_flag").val() === "false") ? "post" : "put",
        data: {
            "token": localStorage.getItem("token"),
            "id": window.parent.$("#blog_id").val(),
            "title": $.trim($("input[name='title']").val()),
            "content": $.trim($("textarea[name='content']").val()),
            "description": $.trim($("textarea[name='description']").val()),
            "type_id": $("select[name='type_id']").val(),
            "create_flag": $("select[name='create_flag']").val(),
            "recommend_level": $("select[name='recommend_level']").val(),
            "tag": tag,
            "image_url": $.trim($("input[name='image_url']").val()),
            "published": published
        },
        dataType: "json",
        traditional: true,//开启传统请求，发送数组数据
        success: function (result) {
            if (result.code === 200) {
                $("button[name='reset_btn']").click();
                layer.msg(result.msg, {icon: 1});
            } else layer.msg(result.msg, {icon: 5});
            layer.close(insert_load_index);
        }
    })
}


/*0.2加载创建标记的函数*/
function load_create_flag(layer, form) {
    $.get("/dic/info", {"token": localStorage.getItem("token"), "dic_type_name": "create_flag"}, function (result) {
        if (result.code === 200) {
            let html_str = "";
            $.each(result.data, function (i, n) {
                html_str += '<option value="' + n.value + '">' + n.dicValueName + '</option>';
            })
            $("select[name='create_flag']").html(html_str);
            form.render("select");//刷新select选择框渲染
            // 0.3 加载推荐级别
            load_recommend_level(layer, form);
        } else layer.msg(result.msg, {icon: 5});
    })
}

/*0.3加载推荐级别的函数*/
function load_recommend_level(layer, form) {
    $.get("/dic/info", {"token": localStorage.getItem("token"), "dic_type_name": "recommend_level"}, function (result) {
        if (result.code === 200) {
            let html_str = "";
            $.each(result.data, function (i, n) {
                html_str += '<option value="' + n.value + '">' + n.dicValueName + '</option>';
            })
            $("select[name='recommend_level']").html(html_str);
            form.render("select");//刷新select选择框渲染
            // 0.4 加载标签
            load_tag(layer, form);
        } else layer.msg(result.msg, {icon: 5});
    })
}

/*0.4加载标签的函数*/
function load_tag(layer, form) {
    $.get("/tagInfo", {"token": localStorage.getItem("token")}, function (result) {
        if (result.code === 200) {
            let html_str = "";
            $.each(result.data, function (i, n) {
                html_str += '<input type="checkbox" name="tag" title="' + n.name + '" value="' + n.id + '">';
            })
            $("#tag_div").html(html_str);
            form.render("checkbox");//刷新checkbox选择框渲染
            // 0.5 加载修改初始化函数
            edit_init(layer, form);
        } else layer.msg(result.msg, {icon: 5});
    })
}

/*0.5修改博客的初始化函数*/
function edit_init(layer, form) {
    if (window.parent.$("#blog_edit_flag").val() === "false") {
        load_editor();//加载editor插件
        layer.closeAll("loading");
        return false;
    }
    let edit_blog_id = window.parent.$("#blog_id").val();
    let edit_blog_published=window.parent.$("#blog_published").val();
    if ($.trim(edit_blog_id) === "") {
        layer.closeAll("loading");
        alert("需要修改的博客id没有找到");
        return false;
    }
    $.get("/blog/info", {
        "token": localStorage.getItem("token"),
        "id": edit_blog_id,
        "published":edit_blog_published
    }, function (result) {
        if (result.code === 200) {
            $("input[name='title']").val(result.data.title);
            $("textarea[name='content']").val(result.data.content);
            $("textarea[name='description']").val(result.data.description);
            $("select[name='type_id']").val(result.data.typeId);
            $("select[name='create_flag']").val(result.data.createFlag);
            $("select[name='recommend_level']").val(result.data.recommendLevel);
            $.each(result.data.tagList, function (i, n) {
                $("input[type='checkbox'][name='tag'][value='" + n.id + "']").prop("checked", true);
            })
            $("input[name='image_url']").val(result.data.imageUrl);
            form.render();// 重新渲染
            load_editor();//加载md插件
        } else layer.msg(result.msg, {icon: 5});
        layer.closeAll("loading");
    })
}

/*0.6加载editor.md插件的函数*/
function load_editor() {
    let testEditor = editormd("md-content", {
        width: "100%",
        height: "640px",
        syncScrolling: "single",
        path: "/lib/editormd/lib/"
    });

    /*
    // or
    testEditor = editormd({
        id      : "test-editormd",
        width   : "90%",
        height  : 640,
        path    : "../lib/"
    });
    */
}